#include "components/controlclass/colorslidbarwidget/hcolorsliderwidget.h"
#include <QColor>
#include <QPainter>
#include <QPaintEvent>
#include <QPixmap>
#include <QLinearGradient>
#include <QPolygonF>
HColorSliderWidget::HColorSliderWidget(QWidget* parent /*= nullptr*/):
	QWidget(parent),
	m_hue(0.0),
	m_iColorwidth(25),
	m_iColorHeight(256)
{
	createHuePixmap();
}

HColorSliderWidget::~HColorSliderWidget()
{

}

void HColorSliderWidget::setHue(int h)
{
	m_hue = (double)h / 360;
	m_iHue = h;
	update();
}

void HColorSliderWidget::paintEvent(QPaintEvent* event)
{
	QPainter painter(this);
	painter.setRenderHint(QPainter::Antialiasing);
	painter.drawPixmap(0, 0, m_huePixmap);
	int iHeight = m_iColorHeight - m_hue * m_iColorHeight;
	QPolygonF triangle;
	triangle.append(QPointF(m_iColorwidth-5,iHeight+topMargin));
	triangle.append(QPointF(width(),iHeight));
	triangle.append(QPointF(width(),iHeight+2*topMargin-1));
	painter.setBrush(QColor("#000000"));
	painter.setPen(Qt::NoPen);
	painter.drawPolygon(triangle);
}

void HColorSliderWidget::mouseMoveEvent(QMouseEvent* event)
{
	double tempValue = 1 - (double)(event->pos().y() - topMargin) / m_iColorHeight;
	m_hue = qBound(0.0, tempValue, 1.0);
	update();
	m_iHue = m_hue * 360;
	emit hueChangedSignal(m_iHue);
}

void HColorSliderWidget::mousePressEvent(QMouseEvent* event)
{
	double tempValue = 1 - (double)(event->pos().y() - topMargin) / m_iColorHeight;
	m_hue = qBound(0.0, tempValue, 1.0);
	update();
	m_iHue = m_hue * 360;
	emit hueChangedSignal(m_iHue);
}

void HColorSliderWidget::createHuePixmap()
{
	m_huePixmap = QPixmap(34, 270);
	m_huePixmap.fill(Qt::transparent);
	QPainter painter(&m_huePixmap);
	painter.setRenderHint(QPainter::Antialiasing);
	QLinearGradient hueGradient(0, m_iColorHeight, 0, 0);
	for (double i =0;i<1.0;i+=1.0/16)
	{
		hueGradient.setColorAt(i, QColor::fromHsvF(i, 1, 1, 1));
	}
	hueGradient.setColorAt(1, QColor::fromHsvF(0, 1, 1, 1));
	painter.setPen(Qt::NoPen);
	painter.setBrush(QBrush(hueGradient));
	painter.drawRect(0, 7, m_iColorHeight, 256);
}
